import React, { useState, useRef, useEffect } from 'react';
import './SmartVideoPage.css';

// 媒体数据接口 (支持视频和图片)
interface VideoData {
  id: number | string;
  aweme_id?: string;
  title: string;
  duration: number;
  play_count: number;
  like_count: number;
  comment_count: number;
  share_count: number;
  cover_url: string;
  video_url: string;
  author: string;
  author_avatar: string;
  create_time: string;
  media_type?: 'video' | 'image'; // 新增媒体类型字段，默认为video
}

// 添加账户数据接口
interface AccountData {
  id: number;
  username: string;
  password: string;
  status: string;
  createdAt: string;
}

// 七牛云上传token接口
interface UploadTokenResponse {
  code: number;
  data: {
    token: string;
    domain: string;
  };
  message: string;
}

const SmartVideoPage: React.FC = () => {
  const [videos, setVideos] = useState<VideoData[]>([
    // 添加一个测试图片项
    {
      id: 'test-image',
      title: '测试图片',
      cover_url: 'https://picsum.photos/400/225?random=1',
      video_url: 'https://picsum.photos/800/450?random=1',
      play_count: 54321,
      like_count: 6789,
      comment_count: 345,
      share_count: 98,
      author: '测试用户',
      author_avatar: 'https://picsum.photos/50/50?random=2',
      create_time: new Date().toISOString().split('T')[0],
      duration: 0,
      media_type: 'image'
    }
  ]);
  const [accounts, setAccounts] = useState<AccountData[]>([
    // 初始化一些模拟账户数据
    {
      id: 1,
      username: "admin",
      password: "admin123",
      status: "active",
      createdAt: "2025-11-15 10:30:00"
    },
    {
      id: 2,
      username: "user1",
      password: "password1",
      status: "inactive",
      createdAt: "2025-11-14 14:20:00"
    }
  ]);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 错误信息状态
  const [error, setError] = useState<string | null>(null);
  // 当前选中的视频
  const [selectedVideo, setSelectedVideo] = useState<VideoData | null>(null);
  // 模态框状态
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [isRefreshing, setIsRefreshing] = useState<boolean>(false);
  const [isAccountModalOpen, setIsAccountModalOpen] = useState<boolean>(false);
  const [isPublishModalOpen, setIsPublishModalOpen] = useState<boolean>(false);
  const [isUserSearchModalOpen, setIsUserSearchModalOpen] = useState<boolean>(false);
  // 当前选中的平台
  const [selectedPlatform, setSelectedPlatform] = useState<string>('全部分类');
  
  // 上传相关状态
  const [isUploading, setIsUploading] = useState<boolean>(false);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [uploadSuccess, setUploadSuccess] = useState<boolean>(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
  
  const [currentAccount, setCurrentAccount] = useState<AccountData | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 获取视频列表
   const fetchVideos = async (platform: string = selectedPlatform) => {
     // 设置加载状态
     setLoading(true);
     setError(null);
    
    try {
        // 使用代理路径访问后端API，避免CORS问题
        let apiPath = '';
        
        if (platform === '小红书') {
          apiPath = '/xiaohongshu-api/api/v1/admin/xiaohongshu/videos';
        } else if (platform === '快手') {
          apiPath = '/kuaishou-api/api/v1/admin/douyin/videos';
        } else if (platform === '抖音') {
          apiPath = '/douyin-api/api/v1/admin/douyin/videos';
        } else {
          // 全部分类，默认使用抖音接口
          apiPath = '/douyin-api/api/v1/admin/douyin/videos';
        }
        
        console.log(`正在从${platform}平台获取数据，URL: ${apiPath}`);
        
        // 使用fetch API发送请求，通过代理访问后端API
        const requestConfig: RequestInit = {
          method: 'GET', // 根据需求，所有平台API都使用GET请求
          headers: {
            'Content-Type': 'application/json',
          }
          // 通过代理请求时，不需要设置credentials，代理会处理请求转发
        };
        
        const response = await fetch(apiPath, requestConfig);
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        console.log(`成功获取${platform}平台视频数据，响应结果:`, result);
      
      // 处理不同API的响应格式
      let videosList: any[] = [];
      
      // 直接检查result是否为数组（有些API可能直接返回数组）
      if (Array.isArray(result)) {
        videosList = result;
      } else if (result.code === 0 || result.data) {
        // 确保我们能处理各种数据格式
        if (Array.isArray(result.data)) {
          // 如果data直接是数组
          videosList = result.data;
        } else if (Array.isArray(result.data?.list)) {
          // 如果data.list是数组（小红书和快手的标准格式）
          videosList = result.data.list;
        } else if (result.data) {
          // 单个视频对象，转换为数组
          videosList = [result.data];
        }
      } else {
        // 如果响应格式不符合预期，尝试将整个响应作为单个视频对象
        videosList = [result];
      }
      
      console.log(`从${platform}平台获取到的视频数量:`, videosList.length);
      
      if (videosList.length === 0) {
        console.warn(`从${platform}平台未获取到任何视频数据`);
      }
      
      // 转换API数据格式以匹配我们的VideoData接口
      const apiVideos: VideoData[] = videosList.map((video: any) => ({
        id: video.id || video.aweme_id || Date.now(),
        aweme_id: video.aweme_id,
        title: video.video_desc || video.title || '未命名视频',
        duration: video.duration || 0,
        play_count: video.play_count || 0,
        like_count: video.digg_count || video.like_count || 0,
        comment_count: video.comment_count || 0,
        share_count: video.share_count || video.forward_count || 0,
        // 清理cover_url中的额外空格和反引号，并确保有默认值
        cover_url: (video.cover_url || 'https://picsum.photos/400/225').toString().trim().replace(/^`|`$/g, ''),
        // 清理video_url中的额外空格和反引号，如果没有则使用cover_url
        video_url: (video.video_url || video.cover_url || '').toString().trim().replace(/^`|`$/g, ''),
        author: video.author_nickname || video.author || video.author_uid || '未知作者',
        author_avatar: (video.author_avatar_url || 'https://picsum.photos/50/50').toString().trim().replace(/^`|`$/g, ''),
        create_time: video.create_time 
          ? new Date((typeof video.create_time === 'number' ? video.create_time : Date.now() / 1000) * 1000).toISOString().split('T')[0]
          : new Date().toISOString().split('T')[0],
        media_type: video.media_type || (video.duration > 0 ? 'video' : 'image') // 根据duration判断媒体类型
      }));
      
      // 直接设置所有获取到的视频数据到视频列表中
      setVideos(apiVideos);
    } catch (err: any) {
      // 优化错误处理，提供更友好的错误提示
      console.error('获取视频数据时出错:', err);
      let errorMessage = `获取${platform}平台数据失败: ${err instanceof Error ? err.message : '未知错误'}`;
      
      if (err instanceof Error) {
        if (err.message.includes('Failed to fetch')) {
          errorMessage = `无法连接到${platform}服务器，请检查网络连接或稍后重试`;
        } else if (err.message.includes('HTTP error')) {
          errorMessage = `服务器返回错误状态，请联系管理员`;
        }
      }
      
      setError(errorMessage);
      console.warn(`为${platform}平台设置默认视频数据以便展示`);
      
      // 设置默认视频数据以便展示
      setVideos([
        {
          id: 'default-test-1',
          title: '测试视频示例',
          cover_url: 'https://picsum.photos/800/450',
          video_url: 'https://picsum.photos/800/450',
          duration: 30,
          play_count: 1000,
          like_count: 100,
          comment_count: 10,
          share_count: 5,
          author: '测试用户',
          author_avatar: 'https://picsum.photos/50/50',
          create_time: new Date().toISOString().split('T')[0],
          media_type: 'video'
        },
        {
          id: 'default-test-2',
          title: '测试图片示例',
          cover_url: 'https://picsum.photos/800/450?random=1',
          video_url: 'https://picsum.photos/800/450?random=1',
          duration: 0,
          play_count: 800,
          like_count: 80,
          comment_count: 8,
          share_count: 4,
          author: '测试用户2',
          author_avatar: 'https://picsum.photos/50/50?random=2',
          create_time: new Date().toISOString().split('T')[0],
          media_type: 'image'
        }
      ]);
    } finally {
        setLoading(false);
      }
  };

  // 获取账户列表（模拟）
  const fetchAccounts = async () => {
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 当前使用模拟数据
      setAccounts(prev => [...prev]); // 触发重新渲染
    } catch (err) {
      console.error('获取账户数据时出错:', err);
      setError('网络错误，请检查连接');
    }
  };

  // 添加或更新账户（模拟）
  const saveAccount = async (account: AccountData) => {
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      if (account.id) {
        // 更新现有账户
        setAccounts(prev => prev.map(acc => acc.id === account.id ? account : acc));
      } else {
        // 添加新账户
        const newAccount = {
          ...account,
          id: Math.max(0, ...accounts.map(a => a.id)) + 1,
          createdAt: new Date().toLocaleString()
        };
        setAccounts(prev => [...prev, newAccount]);
      }
      
      setIsAccountModalOpen(false);
      setCurrentAccount(null);
    } catch (err) {
      console.error('保存账户时出错:', err);
      setError('网络错误，请检查连接');
    }
  };

  // 初始化数据获取
  useEffect(() => {
    // 延迟初始化以确保组件完全加载
    const timer = setTimeout(() => {
      fetchVideos(); // fetchVideos函数现在会使用默认参数selectedPlatform
      fetchAccounts();
    }, 100);
    
    return () => clearTimeout(timer);
  }, [selectedPlatform]);

  // 开始智能抓取
  const handleStartScraping = async() => {
    setLoading(true);
    setError(null);
    
    // 模拟开始抓取过程
    try {
      // 使用与fetchVideos相同的API端点来获取快手视频数据
      const apiPath = 'http://192.168.0.120:3006/api/v1/admin/douyin/videos';
      
      console.log(`正在从快手平台获取数据，URL: ${apiPath}`);
      
      const requestConfig: RequestInit = {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include'
      };
      
      const response = await fetch(apiPath, requestConfig);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('成功获取快手平台视频数据，响应结果:', result);
      
      // 处理不同API的响应格式
      let videosList: any[] = [];
      
      // 直接检查result是否为数组
      if (Array.isArray(result)) {
        videosList = result;
      } else if (result.code === 0 || result.data) {
        // 确保我们能处理各种数据格式
        if (Array.isArray(result.data)) {
          // 如果data直接是数组
          videosList = result.data;
        } else if (Array.isArray(result.data?.list)) {
          // 如果data.list是数组（小红书和快手的标准格式）
          videosList = result.data.list;
        } else if (result.data) {
          // 单个视频对象，转换为数组
          videosList = [result.data];
        }
      } else {
        // 如果响应格式不符合预期，尝试将整个响应作为单个视频对象
        videosList = [result];
      }
      
      console.log('从快手平台获取到的视频数量:', videosList.length);
      
      if (videosList.length === 0) {
        console.warn('从快手平台未获取到任何视频数据');
      }
      
      // 转换API数据格式以匹配我们的VideoData接口
      const apiVideos: VideoData[] = videosList.map((video: any) => ({
        id: video.id || video.aweme_id || Date.now(),
        aweme_id: video.aweme_id,
        title: video.video_desc || video.title || '未命名视频',
        duration: video.duration || 0,
        play_count: video.play_count || 0,
        like_count: video.digg_count || video.like_count || 0,
        comment_count: video.comment_count || 0,
        share_count: video.share_count || video.forward_count || 0,
        // 清理cover_url中的额外空格和反引号，并确保有默认值
        cover_url: (video.cover_url || 'https://picsum.photos/400/225').toString().trim().replace(/^`|`$/g, ''),
        // 清理video_url中的额外空格和反引号，如果没有则使用cover_url
        video_url: (video.video_url || video.cover_url || '').toString().trim().replace(/^`|`$/g, ''),
        author: video.author_nickname || video.author || video.author_uid || '未知作者',
        author_avatar: (video.author_avatar_url || 'https://picsum.photos/50/50').toString().trim().replace(/^`|`$/g, ''),
        create_time: video.create_time 
          ? new Date((typeof video.create_time === 'number' ? video.create_time : Date.now() / 1000) * 1000).toISOString().split('T')[0]
          : new Date().toISOString().split('T')[0],
        media_type: video.media_type || (video.duration > 0 ? 'video' : 'image') // 根据duration判断媒体类型
      }));
      
      // 更新视频列表
      setVideos(apiVideos);
    } catch (err: any) {
      console.error('获取视频数据时出错:', err);
      let errorMessage = `获取快手平台数据失败: ${err instanceof Error ? err.message : '未知错误'}`;
      
      if (err instanceof Error) {
        if (err.message.includes('Failed to fetch')) {
          errorMessage = '无法连接到快手服务器，请检查网络连接或稍后重试';
        } else if (err.message.includes('HTTP error')) {
          errorMessage = '服务器返回错误状态，请联系管理员';
        }
      }
      
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 刷新数据
  const handleRefreshData = () => {
    // 打开发布数据模态框
    openPublishModal();
  };

  // 用户查找功能
  const handleUserSearch = () => {
    // 打开用户查找模态框
    openUserSearchModal();
  };

  // 用户查找提交功能
  const handleUserSearchSubmit = async () => {
    setLoading(true);
    setError(null);
    closeUserSearchModal(); // 关闭模态框
    
    try {
      // 调用抖音个人账号视频抓取接口
      const response = await fetch('/api/v1/command', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          platform: 'douyin',
          command: 'getVideosInfo',
          params: {}
        })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.code === 0) {
        // 成功获取视频信息后更新视频列表
        await fetchVideos();
        console.log('用户视频信息获取成功:', result.message || '操作完成');
      } else {
        throw new Error(result.message || '获取用户视频信息失败');
      }
    } catch (err) {
      console.error('用户查找时出错:', err);
      setError(`用户查找失败: ${err instanceof Error ? err.message : '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 格式化数字显示
  const formatNumber = (num: number): string => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M';
    }
    if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
  };

  // 格式化时间显示
  const formatDuration = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
  };

  // 处理视频点击事件
  const handleVideoClick = (video: VideoData) => {
    setSelectedVideo(video);
  };

  // 关闭账户模态框
  const closeAccountModal = () => {
    setIsAccountModalOpen(false);
    setCurrentAccount(null);
  };

  // 打开发布数据模态框
  const openPublishModal = () => {
    setIsPublishModalOpen(true);
  };

  // 关闭发布数据模态框
  const closePublishModal = () => {
    setIsPublishModalOpen(false);
  };

  // 打开用户查找模态框
  const openUserSearchModal = () => {
    setIsUserSearchModalOpen(true);
  };

  // 关闭用户查找模态框
  const closeUserSearchModal = () => {
    setIsUserSearchModalOpen(false);
  };

  // 打开添加账户模态框
  const openAddAccountModal = () => {
    setCurrentAccount({
      id: 0,
      username: '',
      password: '',
      status: 'active',
      createdAt: ''
    });
    setIsAccountModalOpen(true);
  };

  // 阻止事件冒泡
  const handleModalContentClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  // 获取视频播放链接
  const getVideoUrl = (video: VideoData): string => {
    // 如果视频有真实的URL，使用真实的URL
    if (video.video_url) {
      return video.video_url;
    }
    // 否则返回示例视频链接
    return 'https://www.w3schools.com/html/mov_bbb.mp4';
  };

  // 处理视频或图片加载错误
  const handleVideoError = (e: React.SyntheticEvent<HTMLVideoElement | HTMLImageElement, Event>) => {
    console.error('视频或图片加载出错:', e);
    // 显示错误信息给用户
    setError('媒体资源加载出错，请稍后重试');
    // 可以在这里设置错误状态或显示错误信息
  };

  // 处理视频加载
  const handleVideoLoad = (_e: React.SyntheticEvent<HTMLVideoElement, Event>) => {
    console.log('视频加载成功');
    // 清除之前的错误信息
    if (error && error.includes('视频播放出错')) {
      setError(null);
    }
  };

  // 处理账户表单输入
  const handleAccountInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    if (!currentAccount) return;
    
    const { name, value } = e.target;
    setCurrentAccount({
      ...currentAccount,
      [name]: value
    });
  };

  // 提交账户表单
  const handleAccountSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (currentAccount) {
      saveAccount(currentAccount);
    }
  };

  // 触发文件选择
  const triggerFileSelect = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  // 处理文件选择
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      handleFileUpload(files[0]);
    }
  };

  // 处理文件上传
  const handleFileUpload = async (file: File) => {
    setIsUploading(true);
    setUploadProgress(0);
    setUploadSuccess(false);
    setUploadError(null);
    
    try {
      // 模拟上传进度
      const interval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 95) {
            clearInterval(interval);
            return prev;
          }
          return prev + 5;
        });
      }, 100);
      
      // 模拟上传延迟
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      clearInterval(interval);
      setUploadProgress(100);
      
      // 模拟上传成功
      setUploadSuccess(true);
      
      // 添加上传的视频到列表
      const newVideo: VideoData = {
        id: Date.now(),
        aweme_id: `upload_${Date.now()}`,
        title: file.name,
        duration: 0,
        play_count: 0,
        like_count: 0,
        comment_count: 0,
        share_count: 0,
        cover_url: '',
        video_url: URL.createObjectURL(file),
        author: '本地上传',
        author_avatar: '',
        create_time: new Date().toISOString().split('T')[0],
        media_type: 'video' // 默认为视频类型
      };
      
      // 避免重复添加相同视频
      const isDuplicate = videos.some(existingVideo => 
        existingVideo.aweme_id === newVideo.aweme_id || existingVideo.id === newVideo.id
      );
      
      if (!isDuplicate) {
        setVideos(prev => [newVideo, ...prev]);
      }
      
      // 3秒后清除成功状态
      setTimeout(() => {
        setUploadSuccess(false);
      }, 3000);
    } catch (err) {
      console.error('上传失败:', err);
      setUploadError('上传失败，请重试');
    } finally {
      setIsUploading(false);
      // 清空文件输入框
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  // 添加图片缩略图样式
  useEffect(() => {
    // 检查是否已经添加了样式
    if (!document.getElementById('image-thumbnail-styles')) {
      const style = document.createElement('style');
      style.id = 'image-thumbnail-styles';
      style.textContent = `
        /* 图片缩略图特殊样式 */
        .video-card.image-thumbnail .video-thumbnail {
          border: 2px solid #ddd;
        }
        
        .video-card.image-thumbnail .play-icon {
          display: none;
        }
        
        .video-card.image-thumbnail .duration {
          display: none;
        }
      `;
      document.head.appendChild(style);
      
      // 清理函数
      return () => {
        const styleElement = document.getElementById('image-thumbnail-styles');
        if (styleElement) styleElement.remove();
      };
    }
  }, []);

  return (
    <div className="smart-video-container">
      {/* 隐藏的文件输入框 */}
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: 'none' }}
        accept="video/*"
        onChange={handleFileSelect}
      />
      
      <div className="video-header">
        <div className="header-content">
          <h1 className="page-title">🧠 智能视频抓取平台</h1>
          <p className="page-subtitle">基于AI技术的视频内容智能抓取与分析</p>
        </div>
        <div className="header-actions">
          <button className="upload-btn" onClick={triggerFileSelect} disabled={isUploading}>
            {isUploading ? '📤 上传中...' : '📤 上传视频'}
          </button>
          <button className="upload-btn" onClick={handleStartScraping}>
            📥 开始抓取
          </button>
          <button className="analyze-btn" onClick={handleUserSearch}>
            🔍 用户查找
          </button>
          <button className="analyze-btn" onClick={handleRefreshData} disabled={isRefreshing}>
            {isRefreshing ? '🔄 抓取中...' : '🔄 发布数据'}
          </button>
          <button className="analyze-btn" onClick={openAddAccountModal}>
            👤 账户管理
          </button>
        </div>
      </div>

      {/* 上传进度和状态显示 */}
      {(isUploading || uploadSuccess || uploadError) && (
        <div className="upload-status-section">
          {isUploading && (
            <div className="loading-message">
              <div>正在上传视频... {uploadProgress}%</div>
              <div className="progress-bar">
                <div 
                  className="progress-fill" 
                  style={{ width: `${uploadProgress}%` }}
                ></div>
              </div>
            </div>
          )}
          
          {uploadSuccess && (
            <div className="success-message">
              视频上传成功！
            </div>
          )}
          
          {uploadError && (
            <div className="error-message">
              上传失败: {uploadError}
            </div>
          )}
        </div>
      )}

      <div className="video-content">
        {/* 视频播放区域 - 上方 */}
        <div className="video-player-section">
          <div className="player-header">
            <h2>📺 视频播放区域</h2>
            {selectedVideo && (
              <div className="video-info-display">
                <span className="video-title-display">{selectedVideo.title}</span>
                <span className="video-stats-display">
                  👁️ {formatNumber(selectedVideo.play_count)} 次播放 | 
                  ❤️ {formatNumber(selectedVideo.like_count)} 点赞 | 
                  💬 {formatNumber(selectedVideo.comment_count)} 评论
                </span>
              </div>
            )}
          </div>
          
          {selectedVideo ? (
            <div className="video-player-container">
              {selectedVideo.media_type === 'image' ? (
                <img 
                  src={selectedVideo.video_url || selectedVideo.cover_url}
                  alt={selectedVideo.title}
                  onError={handleVideoError}
                  className="main-video-player main-image-display"
                />
              ) : (
                <video 
                  src={selectedVideo.video_url || getVideoUrl(selectedVideo)}
                  controls
                  autoPlay
                  onError={handleVideoError}
                  onLoad={handleVideoLoad}
                  className="main-video-player"
                />
              )}
            </div>
          ) : (
            <div className="player-placeholder">
              <div className="player-title">请选择一个视频开始播放</div>
              <div className="player-controls">
                <button className="control-btn">▶ 播放</button>
                <button className="control-btn">⏸ 暂停</button>
                <button className="control-btn" onClick={() => setIsModalOpen(true)}>⛶ 全屏</button>
              </div>
            </div>
          )}
        </div>

        {/* 视频列表区域 - 下方 */}
        <div className="video-list-section">
          <div className="section-header">
            <h2>📋 视频资源库</h2>
            <div className="section-actions">
              <select 
                className="filter-select"
                value={selectedPlatform}
                onChange={(e) => {
                  setSelectedPlatform(e.target.value);
                }}
              >
                <option>全部分类</option>
                <option>抖音</option>
                <option>快手</option>
                <option>小红书</option>
              </select>
            </div>
          </div>
          
          {loading && (
            <div className="loading-message">
              正在获取视频数据...
            </div>
          )}
          
          {error && (
            <div className="error-message">
              错误: {error}
            </div>
          )}
          
          <div className="video-grid">
            {loading ? (
              <div className="loading-container">
                <div className="loading-spinner"></div>
                <p>正在加载数据...</p>
              </div>
            ) : error ? (
              <div className="error-message">
                <p>⚠️ {error}</p>
                <p>已使用默认测试数据显示</p>
                <button onClick={() => fetchVideos(selectedPlatform)}>重试</button>
              </div>
            ) : videos.length === 0 ? (
              <div className="empty-message">
                <p>暂无数据</p>
              </div>
            ) : (
              videos.map((video) => (
                <div 
                  key={video.id} 
                  className={`video-card ${selectedVideo?.id === video.id ? 'selected' : ''}`}
                  onClick={() => handleVideoClick(video)}
                >
                  <div 
                    className={`video-thumbnail ${video.media_type === 'image' ? 'image-thumbnail' : ''}`}
                    style={{
                      background: video.cover_url 
                        ? `url(${video.cover_url}) center/cover` 
                        : 'linear-gradient(45deg, #4361ee, #3a0ca3)'
                    }}
                  >
                    {video.media_type !== 'image' && (
                      <>
                        <div className="play-icon">▶</div>
                        <div className="video-duration">{formatDuration(video.duration)}</div>
                      </>
                    )}
                  </div>
                  <div className="video-info">
                    <h3 className="video-title">{video.title}</h3>
                    <div className="video-meta">
                      <span>👤 {video.author}</span>
                      <span>👁️ {formatNumber(video.play_count)}</span>
                    </div>
                    <div className="video-meta">
                      <span>❤️ {formatNumber(video.like_count)}</span>
                      <span>💬 {formatNumber(video.comment_count)}</span>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {/* 账户管理模态框 */}
      {isAccountModalOpen && currentAccount && (
        <div className="video-modal-overlay" onClick={closeAccountModal}>
          <div className="video-modal-content" onClick={handleModalContentClick}>
            <div className="video-modal-header">
              <h2 className="video-modal-title">{currentAccount.id ? '编辑账户' : '添加账户'}</h2>
              <button className="video-modal-close" onClick={closeAccountModal}>×</button>
            </div>
            <div className="video-modal-info">
              <form onSubmit={handleAccountSubmit}>
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>用户名:</label>
                  <input
                    type="text"
                    name="username"
                    value={currentAccount.username}
                    onChange={handleAccountInputChange}
                    style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
                    required
                  />
                </div>
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>密码:</label>
                  <input
                    type="password"
                    name="password"
                    value={currentAccount.password}
                    onChange={handleAccountInputChange}
                    style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
                    required
                  />
                </div>
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>状态:</label>
                  <select
                    name="status"
                    value={currentAccount.status}
                    onChange={handleAccountInputChange}
                    style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
                  >
                    <option value="active">激活</option>
                    <option value="inactive">未激活</option>
                  </select>
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
                  <button 
                    type="button" 
                    className="video-action-button" 
                    onClick={closeAccountModal}
                    style={{ backgroundColor: '#95a5a6' }}
                  >
                    取消
                  </button>
                  <button type="submit" className="video-action-button">
                    保存
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* 发布数据模态框 */}
      {isPublishModalOpen && (
        <div className="video-modal-overlay" onClick={closePublishModal}>
          <div className="video-modal-content" onClick={handleModalContentClick}>
            <div className="video-modal-header">
              <h2 className="video-modal-title">发布抖音视频</h2>
              <button className="video-modal-close" onClick={closePublishModal}>×</button>
            </div>
            <div className="video-modal-info">
              <div style={{ marginBottom: '20px' }}>
                <h3 style={{ marginBottom: '10px' }}>视频信息</h3>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: '15px' }}>
                  <div style={{
                    width: '80px',
                    height: '80px',
                    backgroundColor: '#f0f0f0',
                    borderRadius: '8px',
                    marginRight: '15px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '24px'
                  }}>
                    🎥
                  </div>
                  <div>
                    <div style={{ fontWeight: 'bold' }}>示例视频标题</div>
                    <div style={{ color: '#666', fontSize: '14px' }}>时长: 00:30</div>
                  </div>
                </div>
              </div>
              
              <div style={{ marginBottom: '20px' }}>
                <h3 style={{ marginBottom: '10px' }}>发布设置</h3>
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>标题:</label>
                  <input
                    type="text"
                    placeholder="输入视频标题"
                    style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
                  />
                </div>
                
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>话题标签:</label>
                  <input
                    type="text"
                    placeholder="#生活记录 #春天来了 #樱花季"
                    style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
                  />
                </div>
                
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>视频描述:</label>
                  <textarea
                    placeholder="输入视频描述..."
                    rows={3}
                    style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
                  ></textarea>
                </div>
              </div>
              
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
                <button 
                  type="button" 
                  className="video-action-button" 
                  onClick={closePublishModal}
                  style={{ backgroundColor: '#95a5a6' }}
                >
                  取消
                </button>
                <button 
                  type="button" 
                  className="video-action-button" 
                  style={{ backgroundColor: '#4361ee' }}
                  onClick={handleRefreshData}
                >
                  发布
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 用户查找模态框 */}
      {isUserSearchModalOpen && (
        <div className="video-modal-overlay" onClick={closeUserSearchModal}>
          <div className="video-modal-content" onClick={handleModalContentClick}>
            <div className="video-modal-header">
              <h2 className="video-modal-title">查找抖音用户</h2>
              <button className="video-modal-close" onClick={closeUserSearchModal}>×</button>
            </div>
            <div className="video-modal-info">
              <div style={{ marginBottom: '20px' }}>
                <h3 style={{ marginBottom: '10px' }}>用户信息</h3>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: '15px' }}>
                  <div style={{
                    width: '60px',
                    height: '60px',
                    backgroundColor: '#f0f0f0',
                    borderRadius: '50%',
                    marginRight: '15px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '24px'
                  }}>
                    👤
                  </div>
                  <div>
                    <div style={{ fontWeight: 'bold' }}>用户名</div>
                    <div style={{ color: '#666', fontSize: '14px' }}>用户ID: 123456789</div>
                  </div>
                </div>
              </div>
              
              <div style={{ marginBottom: '20px' }}>
                <h3 style={{ marginBottom: '10px' }}>搜索设置</h3>
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>用户ID/昵称:</label>
                  <input
                    type="text"
                    placeholder="输入用户ID或昵称"
                    style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}
                  />
                </div>
                
                <div style={{ marginBottom: '15px' }}>
                  <label style={{ display: 'block', marginBottom: '5px' }}>搜索范围:</label>
                  <select style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #ddd' }}>
                    <option value="videos">视频</option>
                    <option value="likes">喜欢的视频</option>
                    <option value="following">关注列表</option>
                    <option value="followers">粉丝列表</option>
                  </select>
                </div>
              </div>
              
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
                <button 
                  type="button" 
                  className="video-action-button" 
                  onClick={closeUserSearchModal}
                  style={{ backgroundColor: '#95a5a6' }}
                >
                  取消
                </button>
                <button 
                  type="button" 
                  className="video-action-button" 
                  style={{ backgroundColor: '#4361ee' }}
                  onClick={handleUserSearchSubmit}
                >
                  搜索
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SmartVideoPage;